package com.tianyu.java.Server.Handler;

import com.tianyu.java.Message.*;
import com.tianyu.java.Server.CommonDataTool;
import com.tianyu.java.Server.SmartHomeContextTool;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

/**
 * 描述: 监听客户端上传上来的相关环境信息
 */
public class SmartHomeReadHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel socketChannel;
    //通用数据媒介
    CommonDataTool dataTool = (CommonDataTool) SmartHomeContextTool.instance.getContext().getBean("commonDataTool");

    public SmartHomeReadHandler(AsynchronousSocketChannel channel) {
        this.socketChannel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        //System.out.println("连接状态："+result);
        if (result == -1) {
            System.out.println("断开连接");
            //释放一下信道
            dataTool.removeSocketChannel(socketChannel);
        } else {
            buffer.flip();
            //解析消息
            messageNormalization(buffer);
            buffer.clear();
            //继续监听下一条消息
            socketChannel.read(buffer, buffer, this);
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            exc.printStackTrace();
        } finally {
            System.out.println("结束了");
        }
    }

    /**
     * 描述: 消息的标准化
     */
    public void messageNormalization(ByteBuffer buffer) {
        int length = buffer.limit();
        byte bytes[] = new byte[length];
        buffer.get(bytes, 0, length);
        int index = 0;
        int begin = bytes[index++];
        if (begin == -2) { //数据发送的时候要以十六进制打过来
            String mac = dataTool.getMac(socketChannel);
            if(mac.startsWith("MAC")) { //智能家居
                SmartHomeInfo info = new SmartHomeInfo();
                int[] infos = new int[7];
                for (int i = 0; i < 6; i++) {
                    if (bytes[index] == '-') { //湿度数据也可能是44，笑死，这个分隔符选的
                        index++;
                    }
                    int item = bytes[index++] & 0xff;
                    infos[i] = item;
                }
                //已经往嘴里塞数据了，此处肯定就在线了
                infos[6] = 1;
                info.setInfo(infos);
                System.out.println(info.toString());
                //存储到内存，需要和不同设备的MAC对照起来
                dataTool.setInfo(info, mac);
            }else if(mac.startsWith("XMYZ")) {
                LiveStockInfo liveStockInfo = new LiveStockInfo();
                liveStockInfo.analyse(bytes, length);
                liveStockInfo.setOnline(1);
                System.out.println(liveStockInfo.toString());
                //存储到内存，需要和不同设备的MAC对照起来
                dataTool.setInfo(liveStockInfo, mac);
            }else if(mac.startsWith("HJJC")) {
                EnvironmentInfo environmentInfo = new EnvironmentInfo();
                environmentInfo.analyse(bytes, length);
                environmentInfo.setOnline(1);
                System.out.println(environmentInfo.toString());
                dataTool.setInfo(environmentInfo, mac);
            }
            //设置心跳包
            dataTool.setHeart(mac);
            byte[] result = {(byte) 0xef, 0x77, 0x00};
            socketChannel.write(ByteBuffer.wrap(result), null, new SmartHomeWriteHandler());
        } else if (begin == 77 || begin == 88 || begin == 72) {
            //应该是以MAC打头的硬件MAC地址
            String macStr = new String(bytes);
            System.out.println("MAC地址: "+macStr);
            //把MAC地址和信道的绑定关系存储起来
            dataTool.setSocketChannel(macStr, socketChannel);
        } else {
            byte[] result = {(byte) 0xef, 0x66, 0x00};
            socketChannel.write(ByteBuffer.wrap(result), null, new SmartHomeWriteHandler());
            System.out.println("数据头异常");
        }
    }
}
